﻿using UnityEngine;
using System.Collections;

public class ParticleSystemScaleRumtime_V2 : MonoBehaviour {

    public ParticleSystemRenderer pRenderer;
    public Material dyMaterial;
    public Camera target;
    void OnEnable()
    {
        pRenderer = GetComponent<ParticleSystemRenderer>();
        dyMaterial = pRenderer.material;
        if (pRenderer.renderMode == ParticleSystemRenderMode.Mesh)
        {
            dyMaterial.EnableKeyword("SCALE_ON_MESH");
        }
        else
        {
            dyMaterial.EnableKeyword("SCALE_ON_Bill");
        }


        target = NGUITools.FindCameraForLayer(gameObject.layer);
        testValue = Vector3.one;
    }

    public Vector3 testValue = Vector3.one;
    void OnWillRenderObject()
    {
        if (target != null)
        {
            if (pRenderer.renderMode != ParticleSystemRenderMode.Mesh)
            {
                Vector3 cameraPos = target.worldToCameraMatrix.MultiplyPoint(transform.position);
                dyMaterial.SetVector(Shader.PropertyToID("_Position"), cameraPos);
            }

            dyMaterial.SetVector(Shader.PropertyToID("_Scale"), testValue);
        }
    }

    void OnDisable()
    {
        if (pRenderer.renderMode == ParticleSystemRenderMode.Mesh)
        {
            dyMaterial.EnableKeyword("SCALE_ON_MESH");
        }
        else
        {
            dyMaterial.EnableKeyword("SCALE_ON_Bill");
        }
    }
}
